package com.danbay.framework.web.json;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 统一json输出处理
 * @author SJG
 *         2017/11/16.
 */
@Slf4j
public class FormatJsonReturnValueHandler implements HandlerMethodReturnValueHandler {
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return returnType.getMethodAnnotation(PerfectJson.class) != null || returnType.getMethodAnnotation(PerfectJson.class) != null;
    }

    @Override
    public void handleReturnValue(Object obj, MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest) {
        modelAndViewContainer.setRequestHandled(true);
        HttpServletResponse response=nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter writer = null;
        JsonResult info=new JsonResult();
        info.setCode(200);
        info.setResult(true);
        info.setData(obj);
        try {
            writer = response.getWriter();
            writer.write(new ObjectMapper().writeValueAsString(info));
            writer.flush();
        } catch (IOException ex) {
            log.error("write json error",ex);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
